package cn.itsource.org.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.DataListener;
import cn.itsource.basic.utils.PageResult;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.ShopAuditLog;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.ShopService;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/shop")
@Api(value = "店铺的API", description = "店铺相关的CRUD功能")
public class ShopController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopMapper shopMapper;

    //注意前端地址：http://localhost:8080/shop - get
    //查询所有
    @GetMapping
    @ApiOperation("查询所有")
    public List<Shop> findAll() {
        return shopService.findAll();
    }

    //注意前端地址：http://localhost:8080/shop/1 - get
    //根据id查询
    @GetMapping("/{id}")
    @ApiOperation("根据id查询")
    public Shop findOne(@PathVariable("id") Long id) {
        return shopService.findOne(id);
    }

    //注意前端地址：http://localhost:8080/shop/1 - delete
    //根据id删除
    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            shopService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //注意前端地址：http://localhost:8080/shop - put - {}
    @PutMapping
    @ApiOperation("添加修改")
    public AjaxResult addorUpdate(@RequestBody Shop shop) {
        try {
            if (shop.getId() == null) {//添加操作
                shopService.add(shop);
            } else {
                shopService.update(shop);
            }
            //如果成功
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //注意前端地址：http://localhost:8080/shop - Patch - []
    //批量删除
    @PatchMapping
    @ApiOperation("批量删除")
    public AjaxResult patchdel(@RequestBody Long[] ids) {
        try {
            shopService.patchdel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }

    //分页
    @PostMapping
    @ApiOperation("分页查询")
    public PageResult<Shop> queryPage(@RequestBody ShopQuery shopQuery) {
        return shopService.queryPage(shopQuery);
    }

    //店铺入住信息添加
    @PostMapping("/settlement")
    public AjaxResult settlement(@RequestBody Shop shop) {

        return shopService.settlement(shop);
    }

    //店铺审核通过
    @PostMapping("/auditPass")
    public AjaxResult auditPass(@RequestBody ShopAuditLog shopAuditLog) {
        return shopService.auditPass(shopAuditLog);
    }

    //店铺审核驳回
    @PostMapping("/auditReject")
    public AjaxResult auditReject(@RequestBody ShopAuditLog shopAuditLog) {
        return shopService.auditReject(shopAuditLog);
    }

    //在qq邮箱激活店铺
    @GetMapping("/activation/{id}")
    public void activation(@PathVariable("id") Long id, HttpServletResponse response) {
        shopService.activation(id, response);
    }

    // 柱状图
    @GetMapping("/columnChart")
    public List<Shop> columnChart() {
        return shopService.columnChart();
    }

    //导出Excel接口
    @GetMapping("/exportExcel")
    public void exportExecl(HttpServletResponse response) throws IOException {
        // 从数据库查询出所有的数据
        List<Shop> list = shopService.findAll();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("name", "店铺名称");
        writer.addHeaderAlias("tel", "电话");
        writer.addHeaderAlias("registerTime", "创建时间");
        writer.addHeaderAlias("state", "审核状态");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("logo", "店铺logo");
        writer.addHeaderAlias("adminId", "店铺管理员ID");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("店铺信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    //导入Excel接口
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(), Shop.class, new DataListener(shopMapper)).sheet().doRead();
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
           return new AjaxResult(false,"服务器繁忙请稍后再试【500】");
        }

    }
}
